package com.haruhinav.ws;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.core.JsonParseException;
import com.haruhinav.Utils.ApplicationContextProvider;
import com.haruhinav.Utils.ChatUserUtil;
import com.haruhinav.Utils.TimeTool;
import com.haruhinav.config.WebSocketConfig;
import com.haruhinav.entity.User;
import com.haruhinav.entity.vo.ResultMessageVO;
import com.haruhinav.entity.vo.ResultVO;
import com.haruhinav.entity.vo.SocketMsgVO;
import com.haruhinav.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.util.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 实时聊天室服务类
 */
//@ConditionalOnClass(value = WebSocketConfig.class)
@ServerEndpoint(value = "/chat/{uid}")
@Component
@Slf4j
public class ChatEndpoint {

    private Session session;
    //private Map<String,ChatEndpoint> map = new ConcurrentHashMap<>();
    private int userId;

    public ResultMessageVO resultMessage = new ResultMessageVO();
    private static CopyOnWriteArraySet<ChatEndpoint> chatEndpoints = new CopyOnWriteArraySet<>();


    // 获得bean
    // private UserService userService = ApplicationContextProvider.getBean(UserService.class);
    private UserMapper userMapper = ApplicationContextProvider.getBean(UserMapper.class);
    private TimeTool timeTool = ApplicationContextProvider.getBean(TimeTool.class);
    private ChatUserUtil chatUserUtil = ApplicationContextProvider.getBean(ChatUserUtil.class);

    @OnOpen
    public void onOpen(Session session, @PathParam("uid") int userId) throws Exception {

        User user = userMapper.findUserByIdNoPswd(userId);
        this.session = session;
        this.userId = userId;

        // 将刚上线的用户存入resultMessage
        this.resultMessage.setData(user);
        chatEndpoints.add(this);

          // 每次有用户上线时，将所有（包括刚上线的用户）在线用户
        // 推给所有用户 onLineUsers 里村的时user对象
        List<Object> onLineUsers = chatUserUtil.getOnLineUsers(this.chatEndpoints);

        ResultMessageVO resMsg = new ResultMessageVO();
        // 这个map只有是系统消息时才有
        Map<String, Object> map = new HashMap<>();
        map.put("user", this.resultMessage.getData());
        //map.put("size",chatEndpoints.size());
        map.put("isOpen", true);//表示有人上线
        map.put("onlineUsers", onLineUsers);

        resMsg.fill(2, true, "进入了聊天室", timeTool.getNow(), map);
        String resJson = new ObjectMapper().writeValueAsString(resMsg);
        sendMessage(resJson);
        //System.out.println("有新的连接："+ u.getNickName()+"，总数："+chatEndpoints.size());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();

        log.info("ws发生异常");
    }

    @OnClose
    public void onClose(Session session) throws Exception {

        chatEndpoints.remove(this);
        //User u = (User)this.resultMessage.getData();

        //System.out.println("连接断开，总数："+chatEndpoints.size());

        ResultMessageVO resMsg = new ResultMessageVO();
        Map<String, Object> map = new HashMap<>();

        List<Object> onLineUsers = chatUserUtil.getOnLineUsers(this.chatEndpoints);

        //这个this.resultMessage.getData() 直接是一个user对象
        map.put("user", this.resultMessage.getData());
        //map.put("size",chatEndpoints.size());
        map.put("isOpen", false);//表示有人下线
        map.put("onlineUsers", onLineUsers);

        resMsg.fill(2, true, "离开了聊天室", timeTool.getNow(), map);

        String resJson = new ObjectMapper().writeValueAsString(resMsg);
        sendMessage(resJson);
    }

    @OnMessage
    public void onMessage(String SocketMsg, @PathParam("uid") int userId) throws Exception {
        try {
            SocketMsgVO socketMsg = new ObjectMapper().readValue(SocketMsg, SocketMsgVO.class);
            if (socketMsg.getType() == 1) {
                //私聊
                ResultMessageVO resMsg = new ResultMessageVO();
                boolean flag = true;
                // foreach无法用break跳出循环 所有使用for
                for (ChatEndpoint ce : this.chatEndpoints) {
                    if (ce.userId == socketMsg.getToUserId()) {
                        flag = false;
                        Map<String, Object> resmap = new HashedMap();
                        //resultMessage.getData() 是一个user对象
                        resmap.put("to", ce.resultMessage.getData());
                        resmap.put("from", this.resultMessage.getData());

                        resMsg.fill(1, false, socketMsg.getMsg(), timeTool.getNow(), resmap);
                        String resJson = new ObjectMapper().writeValueAsString(resMsg);
                        // 发送给自己
                        this.session.getBasicRemote().sendText(resJson);
                        // 发送给指定用户(私聊)
                        ce.session.getBasicRemote().sendText(resJson);
                        break;
                    }
                }
                // 没有找到预发送的用户(没有进入上个for循环里的if里去)
                if (flag) {
                    Map<String, Object> resmap = new HashedMap();
                    User u = new User();
                    u.setId(socketMsg.getToUserId());
                    resmap.put("to", u);//这是一个user对象
                    resmap.put("from", userId);
                    resMsg.fill(1, true, "对方已离开聊天室", timeTool.getNow(), resmap);
                    String resJson = new ObjectMapper().writeValueAsString(resMsg);
                    this.session.getBasicRemote().sendText(resJson);
                }
            } else {
                //群聊
                // 在连接的时候，user对象已经set进全局的resultMessage里去了，
                // 所以这里不需要再setData了 此时data是一个use对象

                this.resultMessage.fill(2, false, socketMsg.getMsg(), timeTool.getNow(), this.resultMessage.getData());
                String resJson = new ObjectMapper().writeValueAsString(this.resultMessage);
                // 收到消息后发给所有正在连接中的客户端
                sendMessage(resJson);
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 发给所有客户端 json msg
    public void sendMessage(String message) {
        chatEndpoints.forEach(ce -> {
            try {
                ce.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
